package org.eoti.math.brocot;

import org.eoti.math.Fraction;

import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.math.MathContext;

public class SternBrocotNavigator
{
    private Console console;
    private SternBrocot brocot;

    public static void main(String ... args)
    {
        new SternBrocotNavigator();
    }

    public SternBrocotNavigator()
    {
        brocot = new SternBrocot();
        console = System.console();
        BufferedReader in = new BufferedReader(console.reader());
        boolean done = false;
        while(!done)
        {
            Fraction current = brocot.getFraction();
            String decimal = current.compute(MathContext.DECIMAL128).stripTrailingZeros().toPlainString();
            console.format("\n%s (%s) > ", decimal, current);
            try {
                char c = in.readLine().charAt(0);
                switch(c)
                {
                    case 'q':
                    case 'Q':
                    case 'x':
                    case 'X':
                        done = true;
                        break;
                    case '?':
                    case 'h':
                    case 'H':
                        console.format("\n  Q,q,X,x\tquit\n  ?,h,H\t\thelp\n  b,B\t\tback\n  l,L,<\t\tleft\n  r,R,>\t\tright\n");
                        break;
                    case 'l':
                    case 'L':
                    case '<':
                        brocot.move(SternBrocot.Choice.Left);
                        break;
                    case 'r':
                    case 'R':
                    case '>':
                        brocot.move(SternBrocot.Choice.Right);
                        break;
                    case 'b':
                    case 'B':
                        brocot.move(SternBrocot.Choice.Up);
                        break;
                    default:
                        console.format("Invalid command: try '?'\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
